<?php
require_once 'gadgets.CMS.class.php';
require_once 'recordset.CMS.class.php';
require_once 'image.CMS.class.php';
require_once 'formGenerator.CMS.class.php';

/**
 * Created by Mauro Gadaleta
 * User: Mauro Gadaleta
 * Date: 28/04/11
 * Time: 12:22
 *
 * Clase Base CMS
 */
class CMS {
    /**
     * @var
     */
    public $active = true;

    /**
     * @var 
     */
	private $view;

    /**
     * @var null
     */
	public $id = null;

    /**
     * @var 
     */
	protected $obj;

    /**
     * Constructor set up
     * @param  $view
     */
	function __construct($view) {
        if(!is_null($view))
        {
            $action = $this->setAction($_GET['action']);
            $this->view = $view;
            $this->view->assign('action',$action);
        }
	}

    /**
     * Setea una acción
     * @param  $action
     * @return string
     */
	private function setAction($action) {
		if(is_null($action) && $action == "")
			$action = 'index';
		
		return $action;
	}

    /**
     * Assigna el parametro a Smarty
     * @param  $name
     * @param  $element
     * @return void
     */
	protected function assign($name, $element) {
		if((!is_null($element) || $element != "") && !isset($_GET['display']))
			$this->view->assign($name, $element);
	}

    /**
     * Borra la fila y redirecciona
     * @param  $model
     * @param string $redirect
     * @return void
     */
	protected function delete($model,$redirect = '') {
		$obj = $this->setModel($model);
		$obj->delete();
		if($redirect!='')
			utils::redirect("?module=$redirect",true,true);
	}

    /**
     * Modelo como si fuese un array
     * @param $qry
     * @param bool $debug
     * @return array
     */
	protected function executeToArray($qry,$debug = false) {
		if(isset($_GET['recordsetOrderColumn']) || isset($_GET['recordsetOrder']))
		{
			$qry = $qry->orderby("$_GET[recordsetOrderColumn] $_GET[recordsetOrder]");
		}
		
		if($debug)
			echo $qry->getSqlQuery();
		
		$table = $qry->execute()->toArray();
		
		return $table;
	}

    /**
     * Guarda la fila
     * @param  $data
     * @param bool $redirect
     * @return void
     */
	protected function save($data, $redirect = true) {
		if(!empty($_FILES))
		{
			$images = $this->saveImgs($_FILES);
			if(!is_null($images))
			{
				foreach($images as $value)
				{
					if($value) {
						$data['image'] = $value;
					}
				}	
			}
		}

        $booleanColumns = $this->getBooleanColumns();
        
        if(!is_null($booleanColumns))
        {
            foreach($booleanColumns as $name => $value)
            {
                if(!isset($data[$name]))
                    $this->obj->$name = false;
            }
        }

		$this->obj->setArray($data)->save();
        
		if($redirect && !isset($_GET['ajax']))
			utils::redirect("?module=$this->module",true,true);
	}

    /**
     * Setea el modelo relacional
     * @param  $newObj_s
     * @param  $model
     * @param  $array
     * @return 
     */
	private function setRelatedData($newObj_s, $model, $array) {
		$newObj = $this->setModel($model);
		$newObj_s[$model]['obj'] = $newObj;
		$newObj_s[$model]['data'] = $array;
		
		return $newObj_s;
	}

    /**
     * Setea el modelo
     * @param  $model
     * @param null $id
     * @return doctrine table
     */
	protected function setModel($model , $id = null) {
		if(is_null($id))
		{
            if(isset($this->id) && !is_null($this->id) && $this->id != "")
            {
                $obj = Doctrine::getTable($model)->findOneById($this->id);
            }
            else
            {
                $obj = new $model;
            }
		}
		else
		{
            if(isset($id) && $id != "")
            {
                $obj = Doctrine::getTable($model)->findOneById($id);
            }
			else
            {
                $obj = new $model;
            }
		}

        if(!isset($_GET['display']))
		    $this->view->assign(strtolower($model), $obj);
		
		return $obj;
	}

    /**
     * Lista el modelo
     * @param  $model
     * @param array $params
     * @param bool $debug
     * @return array
     */
	protected function listModel($model, $params = array(), $debug = false) {
		$list = Doctrine_Query::create()
			->from("$model n");
		
		return $this->executeToArray($list,$debug);
	}

    /**
     * @param string $field
     * @param array $list
     * @return array
     */
    protected function deleteFieldFromList($field = '' , $list = array()) {
        foreach($list as $key => $row)
        {
            unset($row[$field]);
            $list[$key] = $row;
        }
        return $list;
    }
	
	/**
     * Ejecuta la acción prestablecida Edit
     * @return void
     */
	public function executeEdit() {
		$this->obj = $this->setModel($this->model);
        
        $action = '?module='.$this->module.'&action=save&id='.$this->id;

        $form = new formGeneratorCMS($this->model, $action);
        $form->setRecord($this->obj);
        $this->assign('form',$form->get());
	}

    /**
     * Ejecuta la acción prestablecida Save
     * @param bool $redirect
     * @param array $data
     * @return void
     */
    public function executeSave($redirect = true , $data=array()) {
        $this->obj = $this->setModel($this->model);
        $data = (empty($data))?$_POST:$data;
        $data = utils::setNullEmptyFieldArray($data);
        if(!$redirect)
            $this->save($data, false);
        else
            $this->save($data, true);
    }

    /**
     * Guarda imagenes
     * @param  $files
     * @return void
     */
	protected function saveImgs($files) {
		foreach($files as $key => $file)
		{
			if($file['error']==0)
			{
				if(is_array($file['name']))
					$names[$key]['image'] = $this->saveImg($key, $file);
				else
					$names['image'] = $this->saveImg($this->model, $file);	
			}
			
		}
		return $names;
	}

    /**
     * Guarda imagen
     * @param  $module
     * @param  $file
     * @return 
     */
	protected function saveImg($module, $file) {
		$name = $file['name'];
		$tmp_name = $file['tmp_name'];
		if(is_array($name) && is_array($tmp_name))
		{
			$name = $name['image'];
			$tmp_name = $tmp_name['image'];
		}
		
		$dir_base = '../'.__MEDIA__IMAGES_PATH.$module.'/'.$name;
		move_uploaded_file($tmp_name, $dir_base);
		
		return $name;
	}

    /**
     * Ejecuta la acción delete
     * @return void
     */
	public function executeDelete() {
		$this->delete($this->model, $this->module);
	}

    /**
     * Ejecuta la acción Vista
     * @return void
     */
	public function executeView() {
		utils::redirect("?service=$this->module&id=$this->id",true,false);
	}

    /**
     * Ejecuta la acción Index
     * @param array $array
     * @return void
     */
	public function executeIndex($array = array()) {
		$list = (empty($array))?$this->listModel($this->model):$array;
		
		$recordSet = new recordsetCMS($list);
		$recordSet->setAction('edit');
		$recordSet->setAction('delete');
        $recordSet->addBooleanColumns($this->getBooleanColumns());
	
		$this->view->assign('recordset',$recordSet->get());
	}

    /**
     * Devuelve las columnas Boleanas de la tabla del modelo
     * @return array
     */
    protected function getBooleanColumns() {
        $table = Doctrine::getTable($this->model);
        foreach($table->getColumns() as $name => $definition)
        {
            if($definition['type']=='boolean' || ($definition['type']=='integer' && $definition['length']==1))
                $columns[$name] = true;
        }
        return $columns;
    }
}

?>